package com.core.client.configuration;

import com.resource.exception.AuthenticationCustomException;
import com.utility.constant.HttpConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

import java.util.Objects;

/**
 * @author: hw
 * @date: 2021/1/20 15:22
 */
@Slf4j
@Configuration
public class FeignConfiguration implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate template) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)authentication.getDetails();
        if (Objects.isNull(details)){
            throw new AuthenticationCustomException("token已失效");
        }
        log.info("Feign 请求添加自定义请求头：");
        template.header(HttpConstant.HEADERS_AUTHORIZATION, HttpConstant.HEADERS_BEARER+details.getTokenValue());
    }
}
